import React from 'react';
import { Redirect } from 'react-router';

import {connect} from 'react-redux'
import { login } from 'redux/action/app';

import { TOKEN_NAME } from 'constant/app';
import NoAuth from 'component/NoAuth';

const mapStateToProps=(state:any)=>{
    return {}
}

const mapDispatchToProps={login}

export function withAuth(Node:any){
    class Auth extends React.Component<any, any> {

        constructor(props: any) {
          super(props);
          this.state = {
            permits:["","/","/noauth","/home","/login","/demo-manage"]
          }
        }
        componentDidMount() {
            this.props.login(this.props.location.pathname)
        }

        checkAuth=()=>{
          return this.state.permits.some((item:any)=>item===this.props.location.pathname)
        }

        renderFinal=()=>{
          if(!localStorage.getItem(TOKEN_NAME))
            return <Redirect to={`/login`}  />

          if(this.checkAuth()){
            return <Node auth={"auth"} {...this.props}/>
          }

          return <NoAuth/>
        }
        public render() {
          return (
            <>
                {
                    this.renderFinal()
                }
            </>
          );
        }
    }
    return connect(mapStateToProps,mapDispatchToProps)(Auth)
}
